import { conditionsParamsType } from '@/controllers/API/assistant'
import dayjs from 'dayjs'
import { dateFormat, platformTypeMap, typeOptionsMap, userTypeMap } from './constants'
import { ConditionsType } from './types'

// 查询条件格式转换
export const formatCondition = (condition: ConditionsType): conditionsParamsType => {
  const { id, type, user, platform, timeRange } = condition
  return {
    id,
    type,
    user,
    platform,
    timeRange: [timeRange[0].valueOf() / 1000, timeRange[1].valueOf() / 1000]
  }
}

// 入参为空时返回[]
export const getArrayResult = (data: []) => {
  return data || []
}

// 拼接生成CSV文件名
export const getCSVTitle = (condition: ConditionsType, name: string) => {
  const { type, user, platform, timeRange } = condition
  return `${name}-按${typeOptionsMap[type]}-${dayjs(timeRange[0]).format(dateFormat)}到${dayjs(timeRange[1]).format(
    dateFormat
  )}-${userTypeMap[user]}-${platformTypeMap[platform]}-的数据`
}
// 生成CSV内容的函数
function convertArrayToCSV(array) {
  console.log('array', array)
  return array.map(row => row.join(',')).join('\n')
}

// 导出CSV文件的函数
export function exportCSVFile(headers, items, fileTitle) {
  if (headers) {
    items.unshift(headers) // 将表头添加到数据的最前面
  }

  // 转换成CSV格式
  const csvContent = convertArrayToCSV(items)

  // 添加BOM头来确保Excel可以正确识别UTF-8编码
  const BOM = '\uFEFF'
  const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })

  // 创建隐藏的可下载链接
  const element = document.createElement('a')
  const url = window.URL.createObjectURL(blob)
  element.setAttribute('href', url)
  element.setAttribute('download', fileTitle)

  // 触发点击事件
  document.body.appendChild(element)
  element.click()
  document.body.removeChild(element)
  window.URL.revokeObjectURL(url) // cleanup the URL object
}

// 将数字乘以 100, 四舍五入后保留两位小数
export function multiplyAndRound(num) {
  const multiplied = num * 100
  return parseFloat(multiplied.toFixed(2))
}
